package cn.geminis.manage.core.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @author Allen
 */
@Entity
@Getter
@Setter
public class Role {

    @Id
    @Column(length = 36)
    private String id;

    @Column(nullable = false, length = 32)
    private String name;

    @ManyToMany
    private Set<Function> functions = new HashSet<>();

    @ManyToMany
    private Set<Role> rolesManage = new HashSet<>();

    @ManyToMany(mappedBy = "rolesManage")
    private Set<Role> rolesManageBy = new HashSet<>();

    @JsonBackReference
    public Set<Role> getRolesManage() {
        return rolesManage;
    }

//    @JsonBackReference
//    public Set<Role> getRolesManageBy() {
//        return rolesManageBy;
//    }

    @PrePersist
    void createId() {
        if (StringUtils.isEmpty(this.id)) {
            this.id = UUID.randomUUID().toString();
        }
    }

    @PreRemove
    void removeRolesManage() {
        this.rolesManageBy.forEach(role -> role.rolesManage.remove(this));
    }
}
